import { Window_Selectable } from "@/windows/Window_Selectable.js";

export class Window_BattleEnemy extends Window_Selectable {
    constructor(width,height) {
        super(width,height,false);
        this.init(width,height);
    }

    init(width,height) {
        this._enemies = [];
        this._lastSelected=-1;

        this.okHandler=null;
        this.cancelHandler=null;

        super.init(width,height);
    }

    destroy(opts){
        super.destroy(opts);
        this._enemies.length=0;
        this.okHandler=null;
        this.cancelHandler=null;
    }

    enemy(index){
        return this._enemies[index];
    }

    column(){return 2;}
    viewColumn(){return 2;}
    row(){return (this.length()+1)>>1;}
    viewRow(){return 4;}
    length(){return this._enemies.length;}

    itemEnabled(index){return super.itemEnabled(index)&&this.enemy(index)?.isAlive();}

    itemWidth(){return this.contentsWidth()/this.viewColumn();}
    itemHeight(){return this.contentsHeight()/this.viewRow();}

    drawItem(index,x,y,width,height) {
        let enemy=this._enemies[index];
        if(enemy){
            this.resetTextColor();
            let name = this._enemies[index].name();
            this.drawText(name, x,y,width,height);
            if(!enemy.isAlive()){
                this.drawLine(x,y,x+width,y+height,'#f00',8);
                this.drawLine(x,y+height,x+width,y,'#f00',8);
            }
        }
    }

    makeItemList(){
        this._enemies=$gameTroop.aliveMembers();
    }

    refresh(){
        this.makeItemList();
        super.refresh();
    }

    setHandler(name,cb){
        if(name=='ok'){
            this.okHandler=cb;
        }else if(name=='cancel'){
            this.cancelHandler=cb;
        }
    }

    onResponse(index){
        this.okHandler?.(this.enemy(index),index);
    }

    onCancel(){
        this.cancelHandler?.();
    }

    onSelectChanged(index,oldIndex){
        this._enemies[oldIndex]?.deselect();
        let enemy=this._enemies[index];
        if(enemy?.isAlive()){
            enemy.select();
        }
    }
}